package cn.sgy.infrastructure.base.initevent;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;

/**
 * @description 应用初始化后置处理器，防止Spring事件被多次执行
 * @author sgy
 * @date 2023-02-28
 */
public class ApplicationContentPostProcessor implements ApplicationListener<ApplicationReadyEvent> {
    private ApplicationContext applicationContext;
    /**
     * 执行标识，防止Spring事件 {@link ApplicationReadyEvent} 有且执行一次
     */
    private boolean executeOnlyOnce = true;

    public ApplicationContentPostProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        synchronized (ApplicationContentPostProcessor.class) {
            if (executeOnlyOnce) {
                applicationContext.publishEvent(new ApplicationInitializingEvent(this));
                executeOnlyOnce = false;
            }
        }
    }
}
